package com.dai.spec.gxk.controller;

import com.dai.spec.common.annotation.Log;
import com.dai.spec.common.constant.DeliveryLocationConstants;
import com.dai.spec.common.core.controller.BaseController;
import com.dai.spec.common.core.domain.AjaxResult;
import com.dai.spec.common.core.page.TableDataInfo;
import com.dai.spec.common.enums.*;
import com.dai.spec.common.exception.base.BaseException;
import com.dai.spec.common.utils.StringUtils;
import com.dai.spec.common.utils.poi.ExcelUtil;
import com.dai.spec.gxk.domain.Course;
import com.dai.spec.gxk.service.CourseService;
import com.dai.spec.gxk.service.TeacherService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 课程信息管理Controller
 *
 * @author daikl
 * @date 2024-02-29
 */
@SuppressWarnings("all")
@RestController
@RequestMapping("/gxk/course")
@Api("课程管理")
public class CourseController extends BaseController {
    private final CourseService courseService;
    private final TeacherService teacherService;

    public CourseController(CourseService courseService, TeacherService teacherService) {
        this.courseService = courseService;
        this.teacherService = teacherService;
    }

    /**
     * 查询课程信息管理列表
     */
    @ApiOperation("查询课程列表")
    @PreAuthorize("@ss.hasPermi('gxk:course:list')")
    @GetMapping("/list")
    public TableDataInfo list(Course course) {
        startPage();
        List<Course> list = courseService.queryList(course);
        return getDataTable(list);
    }

    /**
     * 导出课程信息管理列表
     */
    @ApiOperation("导出课程信息列表")
    @PreAuthorize("@ss.hasPermi('gxk:course:export')")
    @Log(title = "课程信息管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Course course) {
        List<Course> list = courseService.queryList(course);
        List<Course> courseList = list.stream().map(item -> {
            Course coverCourse = this.coverCourse(item);
            return coverCourse;

        }).collect(Collectors.toList());
        ExcelUtil<Course> util = new ExcelUtil<Course>(Course.class);
        util.exportExcel(response, courseList, "课程信息管理数据");
    }

    private static Course coverCourse(Course item) {
        String department = item.getDepartment();
        item.setDepartment(DepartmentType.getValueByCode(department));

        String courseCycle = item.getCourseCycle();
        item.setCourseCycle(CourseCycleType.getValueByCode(courseCycle));

        String type = item.getType();
        item.setType(CourseType.getValueByCode(type));

        String status = item.getStatus();
        item.setStatus(CourseStatus.getValueByCode(status));

        String deliveryType = item.getDeliveryType();
        item.setDeliveryType(DeliveryType.getValueByCode(deliveryType));
        return item;
    }

    /**
     * 获取课程信息管理详细信息
     */
    @ApiOperation("获取课程详细信息")
    @PreAuthorize("@ss.hasPermi('gxk:course:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(courseService.getById(id));
    }

    /**
     * 新增课程信息管理
     */
    @ApiOperation("新增课程")
    @PreAuthorize("@ss.hasPermi('gxk:course:add')")
    @Log(title = "课程信息管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Course course) {
        this.validateCourse(course);
        //课程余量默认为课程容量
        Long plantCounts = course.getPlantCounts();
        course.setLeaveCounts(plantCounts);
        //指派任课老师
        Long teacherId = teacherService.getByName(course.getTeacherName());
        this.checkTeacherId(teacherId);
        this.setOnlineLocation(course);
        return toAjax(courseService.save(course));
    }


    /**
     * 修改课程信息管理
     */
    @ApiOperation("修改课程")
    @PreAuthorize("@ss.hasPermi('gxk:course:edit')")
    @Log(title = "课程信息管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Course course) {
        this.validateCourse(course);
        this.setOnlineLocation(course);
        return toAjax(courseService.updateById(course));
    }

    /**
     * 删除课程信息管理
     */
    @ApiOperation("删除课程")
    @PreAuthorize("@ss.hasPermi('gxk:course:remove')")
    @Log(title = "课程信息管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(courseService.removeByIds(Arrays.asList(ids)));
    }

    private static void checkTeacherId(Long teacherId) {
        if (teacherId == null) {
            throw new BaseException("输入的任课教师不存在，请重新输入！");
        }
    }

    /**
     * 课程字段校验
     *
     * @param course
     */
    private static void validateCourse(Course course) {
        if (null == course.getCredits()) {
            throw new BaseException("课程学分不能为空！");
        }
        if (StringUtils.isEmpty(course.getDepartment())) {
            throw new BaseException("开课院系不能为空!");
        }
        if (StringUtils.isEmpty(course.getCourseCycle())) {
            throw new BaseException("课程周期不能为空!");
        }
        if (null == course.getStartTime()) {
            throw new BaseException("课程开课时间不能为空!");
        }
//        if (StringUtils.isEmpty(course.getLocation())) {
//            throw new BaseException("上课地点不能为空!");
//        }
        if (null == course.getPlantCounts()) {
            throw new BaseException("课程容量不能为空!");
        }
        if (course.getPlantCounts() < 0) {
            throw new BaseException("课程容量必须大于0");
        }
        if (StringUtils.isEmpty(course.getType())) {
            throw new BaseException("课程类型不能为空!");
        }
        if (StringUtils.isEmpty(course.getDeliveryType())) {
            throw new BaseException("开课类型不能为空!");
        }
    }

    /**
     * 当开课类型为线上时，上课地点必须默认为 学习通APP线上上课
     *
     * @param course
     */
    private static void setOnlineLocation(Course course) {

        if (DeliveryType.ONLINE.getCode().equals(course.getDeliveryType())) {
            course.setLocation(DeliveryLocationConstants.ONLINE_LOCATION);
        }
    }
}
